package cn.guozeyiblog.client;

import net.youmi.android.banner.AdSize;
import net.youmi.android.banner.AdView;
import net.youmi.android.diy.DiyManager;

import org.taptwo.android.widget.ViewFlow;
import org.taptwo.android.widget.ViewFlow.ViewSwitchListener;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.guozeyiblog.netutils.HttpUtil;
import cn.guozeyiblog.netutils.JsoupUtils;

import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.SlidingMenu.OnClosedListener;
import com.slidingmenu.lib.SlidingMenu.OnOpenedListener;
/**
 * 博客的主页面
 * @author kutear
 *
 */
public class MainAll extends Activity implements OnClickListener, 
OnItemClickListener, ViewSwitchListener, OnClosedListener, OnOpenedListener {
	private ImageView menuImage;
	private ImageView searchImage;
	private TextView blogText;
	private SlidingMenu menu;
	private LayoutInflater inflater;
	private ViewFlow maincontentViewFlow;
	private String[] menulist; 
	private int currentViewPager = 0;
	private long lastbackkeytime = 0;
	private LinearLayout navMainBarLayout;//主页
	private LinearLayout navWeChatBarLayout;//微语
	private LinearLayout navCateBarLayout;//分类
	private LinearLayout navLinkBarLayout;//链接
	private String blogurl;
	private SharedPreferences preferences;
	private RelativeLayout adlayout;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_all);
		preferences = getSharedPreferences("cn.guozeyiblog.client_preferences", Context.MODE_PRIVATE);
		blogurl = preferences.getString("blogurl", "http://guozeyiblog.cn");
		initView();
		initMenu();
		blogText.setText(preferences.getString("blogname", "枯等街寒又何妨")); 
		menuImage.setOnClickListener(this);
		searchImage.setOnClickListener(this);
		BaseAdapter adapter = new MainAllAdapter(MainAll.this);
		maincontentViewFlow.setAdapter(adapter);
		maincontentViewFlow.setOnViewSwitchListener(this);
		navCateBarLayout.setOnClickListener(this);
		navMainBarLayout.setOnClickListener(this);
		navLinkBarLayout.setOnClickListener(this);
		navWeChatBarLayout.setOnClickListener(this);
		searchImage.setOnClickListener(this);
		clearOtherNavBg(0);
		maincontentViewFlow.setEnabled(false);
		new AsyGetTitle().execute(blogurl);  //取得给定网站的名称
		//AdView adView = new AdView(getApplicationContext(), AdSize.FIT_SCREEN);
		//adlayout.addView(adView);
	}
	/**
	 * 组件的初始化
	 */
	private void initView(){
		menuImage = (ImageView) findViewById(R.id.menu_ImageView);
		searchImage = (ImageView) findViewById(R.id.search_ImageView);
		blogText = (TextView) findViewById(R.id.blogname_TextView);
		maincontentViewFlow = (ViewFlow) findViewById(R.id.viewflow);
		navCateBarLayout = (LinearLayout) findViewById(R.id.nav_bar2);
		navLinkBarLayout = (LinearLayout) findViewById(R.id.nav_bar4);
		navMainBarLayout = (LinearLayout) findViewById(R.id.nav_bar1);
		navWeChatBarLayout = (LinearLayout) findViewById(R.id.nav_bar3);
		//adlayout = (RelativeLayout) findViewById(R.id.adLayout);
	}
	/**
	 * 旁侧菜单的初始化
	 */
	private void initMenu() {
		menulist = getResources().getStringArray(R.array.menulistarray);
		menu = new SlidingMenu(getApplicationContext());
		menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);  
		menu.setShadowWidthRes(R.dimen.shadow_width);  
		menu.setShadowDrawable(R.drawable.shadow);  
		menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);  
		menu.setFadeDegree(0.35f);  
		menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);  
		inflater = LayoutInflater.from(getApplicationContext());
		LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.menu, null);
		ListView menuListView = (ListView) layout.findViewById(R.id.menu_list);
		ImageView menuImageView = (ImageView) layout.findViewById(R.id.menu_ImageView);
		ImageView exitImageView = (ImageView) layout.findViewById(R.id.exit);
		//-----------------------广告---------------------------------------
		adlayout = (RelativeLayout)(layout.findViewById(R.id.adLayout));
		AdView adView = new AdView(MainAll.this, AdSize.FIT_SCREEN);
		if(adlayout!=null){
			adlayout.addView(adView);
		}
		
		exitImageView.setOnClickListener(this);
		BaseAdapter adapter = new MenuListAdapter();
		menuListView.setAdapter(adapter);
		menu.setMenu(layout);
		menu.setOnClosedListener(this);
		menu.setOnOpenedListener(this);
		menuListView.setOnItemClickListener(this);
	}
	@Override
	/**
	 * 主页按钮监听
	 */
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = null ;
		Log.v("MainAll", "OnClick");
		switch (v.getId()) {
		case R.id.menu_ImageView:  //旁侧菜单
			menu.setSlidingEnabled(true);
			menu.toggle();
			break;
		case R.id.exit:            //旁侧的退出按钮
			super.finish();  
			//退出后台线程,以及销毁静态变量  
			System.exit(0);  
			break;
		case R.id.search_ImageView:
			intent = new Intent(getApplicationContext(), SearchActivity.class);
			startActivity(intent);
			break;
		case R.id.nav_bar1:       //主页
			MainAllAdapter.notifyarticledatachange();
			maincontentViewFlow.setSelection(0);
			break;
		case R.id.nav_bar2:       //分类
			MainAllAdapter.notiycatedatachange();
			maincontentViewFlow.setSelection(1);
			break;
		case R.id.nav_bar3:       //微语
			MainAllAdapter.notifywechatdatachange();
			maincontentViewFlow.setSelection(2);
			break;
		case R.id.nav_bar4:       //链接
			MainAllAdapter.notifylinkdatachange();
			maincontentViewFlow.setSelection(3);
			break;

		default:
			break;
		}

	}

	@Override
	/**
	 * 菜单监听 主要实现页面的跳转
	 */
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		//Toast.makeText(getApplicationContext(), menulist[position], 0).show();
		switch (position) {
		case 0:       //跳转到主页
			maincontentViewFlow.setSelection(0);
			break;
		case 1:       //设置
            Intent intent_setting = new Intent(getApplicationContext(),SettingActivity.class);
            startActivity(intent_setting);
			break;
		case 2:       //天气
            Intent intent_weather = new Intent(getApplicationContext(), WeatherActivity.class);
            startActivity(intent_weather);
			break;
		case 3:       //更新
			Intent intent_update = new Intent(getApplicationContext(), UpdateActivity.class);
            startActivity(intent_update);
			break;
		case 4:       //反馈
			Intent intent_feedback = new Intent(getApplicationContext(), FeedBack.class);
            startActivity(intent_feedback);
			break;
		case 5:       //关于
			Intent intent_about = new Intent(getApplicationContext(), AboutMe.class);
            startActivity(intent_about);
			break;
		case 6:       //应用
			DiyManager.showRecommendWall(MainAll.this);
			break;
		case 7:       //游戏
			DiyManager.showRecommendGameWall(MainAll.this);
			break;

		default:
			break;
		}
		menu.toggle();
	}

	@Override
	/**
	 * ViewFlow 切换监听
	 */
	public void onSwitched(View view, int position) {
		// TODO Auto-generated method stub
		clearOtherNavBg(position);
		//Toast.makeText(getApplicationContext(), position+"", 0).show();
		if (position==0) {
			menu.setSlidingEnabled(true);
		}else {
			menu.setSlidingEnabled(false);
		}
		currentViewPager = position;
		switch (position) {
		case 0:
			
			MainAllAdapter.notifyarticledatachange();
			MainAllAdapter.articlelistView.invalidate();
			break;
		case 1:
			
			MainAllAdapter.notiycatedatachange();
			MainAllAdapter.catelistView.invalidate();
			break;
		case 2:
			MainAllAdapter.notifywechatdatachange();
			MainAllAdapter.wechatlistView.invalidate();
			break;
		case 3:
			MainAllAdapter.notifylinkdatachange();
			MainAllAdapter.linkListView.invalidate();
			break;

		default:
			break;
		}
		
	}
	

	/**
	 * 清除navBar的背景
	 * @param own
	 */
	private void clearOtherNavBg(int own){
		navCateBarLayout.setBackgroundResource(R.color.default_bar);
		navLinkBarLayout.setBackgroundResource(R.color.default_bar);
		navMainBarLayout.setBackgroundResource(R.color.default_bar);
		navWeChatBarLayout.setBackgroundResource(R.color.default_bar);
		switch (own) {
		case 0:
			navMainBarLayout.setBackgroundResource(R.color.lightskyblue);
			break;
		case 1:
			navCateBarLayout.setBackgroundResource(R.color.lightskyblue);
			break;
		case 2:
			navWeChatBarLayout.setBackgroundResource(R.color.lightskyblue);
			break;
		case 3:
			navLinkBarLayout.setBackgroundResource(R.color.lightskyblue);
			break;

		default:
			break;
		}
	}

	@Override
	/**
	 * 退出监听
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK ) {
			if (System.currentTimeMillis()-lastbackkeytime<2000) {
				super.finish();
				System.exit(0);
			}else {
				lastbackkeytime = System.currentTimeMillis();
				Toast.makeText(getApplicationContext(), getResources().getString(R.string.exit_tips), 0).show();
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClosed() {
		// TODO Auto-generated method stub
		Log.v("Main_OnClosed", "OnClosed");
		//maincontentViewFlow.setEnabled(true);
		if (currentViewPager!=0) {
			menu.setSlidingEnabled(false);
		}
	}
	@Override
	public void onOpened() {
		// TODO Auto-generated method stub
		Log.v("Main_onOpened", "onOpened");
		//maincontentViewFlow.setEnabled(false);
	}

	/**
	 * 菜单的listview的适配器
	 * @author kutear
	 *
	 */
	class MenuListAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return menulist.length;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return menulist[position];
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			LinearLayout layout;
			if (convertView==null) {
				layout = (LinearLayout) inflater.inflate(R.layout.menu_item, null);
			}else {
				layout = (LinearLayout) convertView;
			}
			TextView menutext = (TextView) layout.findViewById(R.id.menu_item_textView);
			menutext.setText(menulist[position]);
			return layout;
		}
	}
	/**
	 * 消息处理
	 */
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			
		};
	};
	
	/**
	 * 获取标题
	 */
	public class AsyGetTitle extends AsyncTask<String, String, String>{

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			String result = HttpUtil.httpGet(params[0]);
			publishProgress(JsoupUtils.GetBlogTitle(result));
			return null;
		}
		@Override
		protected void onProgressUpdate(String... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
			blogText.setText(values[0]);
			blogText.invalidate();
			Editor editor = preferences.edit();
			editor.putString("blogname", values[0]);
			editor.commit();
			//Toast.makeText(getApplicationContext(), values[0], 0).show();
		}
		
	}
}